<template>
  <q-layout class="cc-main-layout" view="lhh lpR lff">
    <q-header class=" bg-primary text-white">
      <q-toolbar class="row">
        <q-btn flat icon="menu" @click="drawer = !drawer" />
        <q-tabs inline-label v-model="subSystem" align="left" indicator-color="positive" class="text-white col">
          <q-tab v-for="sub in subSystemList" :key="sub.id" :name="sub.id" :icon="sub.icon" :label="sub.name" @click="subClick(sub)" />
        </q-tabs>

        <q-space />
        <message />
        <div v-if="$q.screen.gt.sm">
          <q-btn icon="mdi-badge-account-horizontal" flat :label="welcomeInfo">
            <q-menu transition-show="rotate" transition-hide="rotate">
              <q-list style="min-width: 160px">
                <q-item clickable @click="updPsw">
                  <q-item-section>修改密码</q-item-section>
                </q-item>

                <q-separator />
              </q-list>
            </q-menu>
          </q-btn>
        </div>
        <q-btn flat icon="mdi-power-standby" label="退出系统" @click="out" />
      </q-toolbar>
      <mainTabs :navList="$store.state.Rule.routeTabs" @changeTab="setDesTab" />
    </q-header>
    <q-drawer elevated v-model="drawer" :overlay="overlay" :width="240" content-class="column">
      <div flat class="ly-icon-btn bg-primary text-white non-selectable">
        <q-icon name="img:icons/logo/logo.png" size="sm" class="q-ml-sm q-mr-md" />考研系统
      </div>
      <div>
        <ship-type ref="shipTypeDialog" :selective="selective" @childMethod="shipMenu" @shipTypeGo="shipTypeGo" />
      </div>
      <div class="col main-menu">
        <q-list>
          <base-menu-item :menuList="menuList" :level="1" ref="baseMenuItem" />
        </q-list>
      </div>
    </q-drawer>

    <q-page-container>
      <router-view v-if="isRouterAlive" />
    </q-page-container>
    <change-password :username="username" ref="changePassWord" />
  </q-layout>
</template>

<script>
import { openURL, copyToClipboard, debounce } from 'quasar';
import message from 'components/layout/message.vue';
import mainTabs from 'components/layout/tabpanel/index.vue';
import { resetRouter } from 'src/router';
import ChangePassword from 'components/sys/change-password.vue';
import baseMenuItem from './baseMenuItem';
import shipType from './shipType';

export default {
  name: 'IndexLayout',
  components: {
    mainTabs,
    baseMenuItem,
    shipType,
    ChangePassword,
    message
  },
  provide() {
    return {
      reload: this.reload,
    };
  },
  data() {
    return {
      isRouterAlive: true,
      subSystem: '',
      subSystemList: [],
      menuList: [],
      selectItem: '',
      link: 'inbox',
      drawer: true,
      overlay: false,
      list: [],
      password: '',
      confirmpassword: '',
      selective: {}
    };
  },
  methods: {
    updPsw() {
      this.$refs.changePassWord.show();
    },
    subClick(sub) {
      if (sub.name === 'SMS') {
        if (this.$store.state.User.info.shipType) {
          this.shipMenu(this.$store.state.User.info.shipType);
        } else {
          this.$refs.shipTypeDialog.selectiveShipType();
        }
      }
      const { routes } = this.$store.state.Rule;
      routes.forEach((route) => {
        if (route.subSystem === sub.id) {
          // 内部还是外部
          if (route.meta.internalOrExternal) {
            openURL(route.fullPath);
          } else {
            this.subSystem = sub.id;
            this.renderSubSystemMenu();
            const to = route.children[0];
            this.$store.commit('Rule/clearRouteTabs');
            this.$store.commit('Rule/addRouteTabs', { name: to.meta.title, path: to.path, fullPath: to.fullPath });
            this.$router.push(to.fullPath);
          }
        }
      });
      this.selective = sub;
      if (this.selective.name === 'SMS') {
        this.selective.shipType = true;
      } else {
        this.selective.shipType = false;
      }
    },
    reload() {
      this.isRouterAlive = false;
      this.$nextTick(() => {
        this.isRouterAlive = true;
      });
    },
    shipTypeGo() {
      this.$refs.baseMenuItem.shipTypeGo();
    },
    doResize() {
      this.drawer = this.$q.screen.gt.sm;
      this.overlay = this.$q.screen.lt.sm;
    },
    setDesTab(val) {
      this.selectItem = val;
    },
    out() {
      this.$axios.get('/sys/logout').then(() => {
        this.$store.commit('User/clear');
        this.$store.commit('Rule/clear');
      }).finally(() => {
        resetRouter();
        window.location.replace('#/login');
      });
    },
    go(u) {
      if (u.internalOrExternal) {
        openURL(u.path);
      } else if (u.path !== this.$route.path) {
        this.$router.push(u);
      }
    },
    headerStyleActive(item) {
      if (this.$route.path.startsWith(item.path)) {
        return {
          color: '#1890ff',
        };
      }
      return {};
    },
    openMenu(item) {
      if (this.$route.path.startsWith(item.path)) {
        return true;
      }
      return false;
    },
    itemStyleActive(item) {
      if (item.path === this.$route.path) {
        return {
          color: '#1890ff',
          backgroundColor: '#e6f7ff',
          borderRight: '0.2em solid #1890ff',
        };
      }
      return {};
    },
    addRouteTab(to) {
      // 登录页面不应该添加到路由导航里面,如果是研发平台的功能，那么这里就不做控制
      this.$store.commit('Rule/addRouteTabs', { name: to.meta.title, path: to.path, fullPath: to.fullPath });
    },
    findSubSystem(child, result) {
      if (child.fullPath === this.$router.currentRoute.fullPath) {
        result.find = true;
        this.addRouteTab(child);
      } else if (child.children) {
        child.children.forEach((subChlid) => {
          this.findSubSystem(subChlid, result);
        });
      }
    },
    renderSubSystemMenu() {
      const { routes } = this.$store.state.Rule;
      this.subSystemList = JSON.parse(localStorage.subSystemList);
      if (!this.subSystem && this.subSystemList && this.subSystemList.length > 0) {
        routes.forEach((route) => {
          if (route.children) {
            route.children.forEach((child) => {
              const result = { find: false };
              this.findSubSystem(child, result);
              if (result.find) {
                if (route.subSystem) {
                  this.subSystem = this.subSystemList.filter((subSystem) => route.subSystem === subSystem.id)[0].id;
                  const subsystem = this.subSystemList.filter((subSystem) => route.subSystem === subSystem.id)[0];
                  this.selective = subsystem;
                  if (this.selective.name === 'SMS') {
                    this.selective.shipType = true;
                    this.$refs.shipTypeDialog.init();
                  } else {
                    this.selective.shipType = false;
                  }
                }
              }
            });
          }
        });
      }
      // 如果当前是SMS子系统，那么就应该统计处理条数
      routes.forEach((route) => {
        if (route.subSystem === this.subSystem) {
          if (route.meta.title === 'SMS') {
            this.$axios.get('/sys/permission/queryShipTypeTreeList', {
              params: { shipType: localStorage.shipTypeCode }
            }).then((r) => {
              if (r.result !== null && r.result.menu[0]) {
                this.menuList = JSON.parse(JSON.stringify(r.result.menu[0].children));
                localStorage.smsMenuList = JSON.stringify(this.menuList);
                this.$root.$emit('showWorkSpace');
                this.calcDealCount(this.menuList);
              }
            });
          } else {
            this.menuList = JSON.parse(JSON.stringify(route.children));
            this.calcDealCount(this.menuList);
          }
        }
      });
    },
    shipMenu(v) {
      // this.menuList.splice(0, this.menuList.length);
      this.$axios.get('/sys/permission/queryShipTypeTreeList', {
        params: { shipType: v }
      }).then((r) => {
        if (r.result !== null && r.result.menu) {
          this.menuList = JSON.parse(JSON.stringify(r.result.menu[0].children));
          localStorage.smsMenuList = JSON.stringify(this.menuList);
          this.$root.$emit('showWorkSpace');
        } else {
          this.menuList = [];
        }
      });
    },
    changeSubSystem(children, fullPath, subSystem) {
      if (children && children.length > 0) {
        children.forEach((child) => {
          if (child.fullPath === fullPath) {
            this.subSystem = subSystem;
            this.renderSubSystemMenu();
          }
          if (child.children && child.children.length > 0) {
            this.changeSubSystem(child.children, fullPath, subSystem);
          }
        });
      }
    },
    calcDealCount(menuList) {
      menuList.forEach((item) => {
        if (item.statUrl !== '' && item.statUrl !== null) {
          this.$axios.get(item.statUrl).then((result) => {
            this.$set(item, 'num', result.result);
            this.calcParentDealCount();
          });
        }
        if (item.children) {
          this.$set(item, 'num', 0);
          this.calcDealCount(item.children);
        }
      });
    },
    doCalcParentDealCount() {
      this.menuList.forEach((item) => {
        if (item.children) {
          const num = this.calcChildCount(item.children);
          item.num = num;
        }
      });
    },
    calcChildCount(menuList) {
      let count = 0;
      menuList.forEach((item) => {
        if (item.children) {
          const num = this.calcChildCount(item.children);
          if (num > 0) {
            item.num = num;
            count += item.num;
          }
        } else if (item.num && item.num > 0) {
          count += item.num;
        }
      });
      return count;
    },
  },
  mounted() {
    this.calcParentDealCount = debounce(this.doCalcParentDealCount, 1000);
    this.onResize = debounce(this.doResize, 500);
    this.onResize();
    this.renderSubSystemMenu();
  },
  watch: {
    screenWidth() {
      this.onResize();
    },
  },
  computed: {
    welcomeInfo() {
      return `欢迎您，${this.$store.state.User.info.realname}`;
    },
    screenWidth() {
      return this.$q.screen.width;
    },
    allMenuList() {
      return this.menuList.map((m) => ({ ...m, num: 0 }));
    },
    username() {
      return this.$store.state.User.info.username;
    }
  },
};
</script>

<style lang="stylus">
.cc-active-menu
  border-right '0.2em solid #1890ff'
.hide-icon
  display none
.ly-icon-btn
  line-height 50px
  height 50px
  border-bottom 1px $sky solid
  border-radius 0
.q-item__section--main ~ .q-item__section--side
  padding-left 0
.main-menu
  .q-item
    min-height 35px
.cc-main-layout
  .q-header .q-tab__content, .q-footer .q-tab__content {
      min-width: 80px;
  }
</style>
